<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="80px">
      <el-row>

        <el-form-item label="业务标题" prop="cmsTitle">
          <el-input  v-model="queryParams.cmsTitle" placeholder="请输入标题" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="业务分类">
          <el-select v-model="queryParams.cmsClassCode" placeholder="请选择分类" clearable size="small">
            <el-option v-for="dict in cmsClassType" :key="dict.cmsClassUid" :label="dict.cmsClassName"
              :value="dict.cmsClassCode" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="dataStatus">
          <el-select v-model="queryParams.dataStatus" placeholder="请选择状态" clearable size="small">
            <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item style="margin-left: 22px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>

      </el-row>
    </el-form>
    <el-row class="row-mbinfo" style="margin-left: 0px;">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['platform:cms:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px;">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['platform:cms:remove']">删除
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="divTable">
      <el-table border v-loading="loading" :data="cmsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="业务Banner" align="center" prop="titleImgUrl" v-if="0>1">
          <template slot-scope="scope">
            <el-image v-if="scope.row.titleImgUrl != null && scope.row.titleImgUrl != '' " slot="reference"
              :src="scope.row.titleImgUrl" class="image-rows" :preview-src-list="[scope.row.titleImgUrl]"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="业务标题" align="center" prop="cmsTitle" :show-overflow-tooltip="true" />
        <el-table-column label="业务分类" align="center">
          <template slot-scope="scope">
            <span> {{ scope.row.cmsClassName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center" prop="publishTime" width="180" sortable>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="dataStatus">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.dataStatus" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="dataPriority" :show-overflow-tooltip="true" sortable />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" sortable>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleShowDetail(scope.row)"
              v-hasPermi="['platform:cms:query']">查看
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['platform:cms:edit']">修改
            </el-button>
            <el-button v-if="scope.row.dataStatus == 0 " size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)" v-hasPermi="['platform:cms:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改(资讯/平台/公告)信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="业务标题" prop="cmsTitle">
          <el-input class="as" v-model="form.cmsTitle" placeholder="请输入业务标题" />
        </el-form-item>

        <el-form-item label="业务分类" prop="cmsTitle">
          <el-select v-model="form.cmsClassCode" placeholder="请选择分类" clearable size="small">
            <el-option v-for="dict in cmsClassType" :key="dict.cmsClassCode" :label="dict.cmsClassName"
              :value="dict.cmsClassCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="dataPriority">
          <el-input-number v-model="form.dataPriority" placeholder="请输入排序" controls-position="right" :min="0"
            :max="999999" />
        </el-form-item>

        <el-form-item label="图片" prop="titleImgUrl">
          <imageArraySize style="margin-left: -40px;" :imageStr.sync="form.titleImgUrl" :key="form.titleImgUrl"
            :msg="'图片要求：宽1170px或750px，高428px或27px，大小2M内。'" :limit="5"></imageArraySize>
        </el-form-item>

        <el-form-item label="业务内容" prop="cmsContent">
          <editor v-model="form.cmsContent" :min-height="192" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看(资讯/平台/公告)信息对话框 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="700px" append-to-body>
      <el-form ref="detailForm" label-width="80px">
        <el-divider content-position="left"><span style="font-size:20px">业务信息</span></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业务标题" style="margin-bottom:10px;">
              <span>{{showData.cmsTitle }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务分类" style="margin-bottom:10px;">
              <span>{{ showData.cmsClassPname}} - {{ showData.cmsClassName}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" style="margin-bottom:10px;">
              <span v-if="showData.dataStatus == 1">有效</span>
              <span v-if="showData.dataStatus == 0">无效</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" style="margin-bottom:10px;">
              <span>{{ showData.dataPriority}} </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="创建人" style="margin-bottom:10px;">
              <span>{{ showData.createName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" style="margin-bottom:10px;">
              <span>{{ parseTime(showData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }} </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="更新人" style="margin-bottom:10px;">
              <span>{{ showData.updateName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" style="margin-bottom:10px;">
              <span>{{ parseTime(showData.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }} </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="发布人" style="margin-bottom:10px;">
              <span>{{ showData.publishUser }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间" style="margin-bottom:10px;">
              <span>{{ parseTime(showData.publishTime, '{y}-{m}-{d} {h}:{i}:{s}') }} </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left"><span style="font-size:20px">业务内容</span></el-divider>
        <span>{{ showData.cmsContent }}</span>

        <el-divider content-position="left"><span style="font-size:20px">图片</span></el-divider>
        <el-image :z-index="zIndex" :preview-src-list="cmsImg" v-for="(imgm,index) in cmsImg" :src="cmsImg[index]"
          :key="index" style="width: 80px;height: 80px;margin-left: 10px">
        </el-image>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handCloseDetail">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listCms,
    getCms,
    delCmsN,
    addCms,
    updateCms,
    updateCmsStatus
  } from "@/api/platform/cms";
  import imageArraySize from "@/components/ImageUpload/imageArraySize";
  import videoUpload from "@/components/ImageUpload/videoUpload";

  import {
    listCmsClass
  } from "@/api/platform/cmsClass"
  import Editor from '@/components/Editor';

  export default {
    name: "Cms",
    components: {
      Editor,
      imageArraySize,
      videoUpload
    },
    data() {
      return {
        zIndex: 3000,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        //选中数组的名字
        names: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // (资讯/平台/公告)信息表格数据
        cmsList: [],
        // 弹出层标题
        title: "",
        //查看详细标题
        viewTitle: "",
        // 是否显示弹出层
        open: false,
        //是否显示查看详细弹出层
        // 常用数据状态字典
        statusOptions: [],
        viewOpen: false,
        //查看详细数据
        showData: [],
        queryParam: {
          cmsClassPname: '业务模块'
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          cmsType: 'notice',
          cmsTitle: null,
          titleImgUrl: null,
          cmsContent: null,
          cmsLink: null,
          publishTime: null,
          publishUser: null,
          dataPriority: null,
          dataStatus: null,
          createUid: null,
          createName: null,
          createTime: null,
          updateUid: null,
          updateName: null,
          updateTime: null,
          recommend: null,
          titleVideoUrl: null,
          cmsClassCode: null,
          cmsClassPcode: null,
          platformUid: null
        },
        columns: [{
            label: '平台ID',
            dataIndex: 'cmsUid',
          },
          {
            label: '类型(notice公告/platformInfo平台信息/information资讯）',
            dataIndex: 'cmsType',
          },
          {
            label: '标题(项目名称)',
            dataIndex: 'cmsTitle',
          },
          {
            label: '标题图片',
            dataIndex: 'titleImgUrl',
          },
          {
            label: '资讯内容',
            dataIndex: 'cmsContent',
          },
          {
            label: '链接',
            dataIndex: 'cmsLink',
          },
          {
            label: '发布时间',
            dataIndex: 'publishTime',
          },
          {
            label: '发布人',
            dataIndex: 'publishUser',
          },
          {
            label: '排序',
            dataIndex: 'dataPriority',
          },
          {
            label: '状态（1有效发布/0未发布)',
            dataIndex: 'dataStatus',
          },
          {
            label: '状态（1有效发布/0未发布)',
            dataIndex: 'createUid',
          },
          {
            label: '状态（1有效发布/0未发布)',
            dataIndex: 'createName',
          },
          {
            label: '状态（1有效发布/0未发布)',
            dataIndex: 'createTime',
          },
          {
            label: '状态（1有效发布/0未发布)',
            dataIndex: 'updateUid',
          },
          {
            label: '状态（1有效发布/0未发布)',
            dataIndex: 'updateName',
          },
          {
            label: '状态（1有效发布/0未发布)',
            dataIndex: 'updateTime',
          },
          {
            label: '是否推荐,0不推荐，1推荐',
            dataIndex: 'recommend',
          },
          {
            label: '视频',
            dataIndex: 'titleVideoUrl',
          },
          {
            label: '资讯类别',
            dataIndex: 'cmsClassCode',
          },
          {
            label: '资讯上级类别',
            dataIndex: 'cmsClassPcode',
          },
          {
            label: '平台ID',
            dataIndex: 'platformUid',
          },
        ],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          cmsTitle: [{
            required: true,
            message: "业务标题不能为空",
            trigger: "blur"
          }],
          dataPriority: [{
            required: true,
            message: "排序名称不能为空",
            trigger: "blur"
          }],
          cmsClassCode: [{
            required: true,
            message: "分类不能为空",
            trigger: "blur"
          }]
        },
        cmsClassType: [],
        cmsImg: [],
      };
    },
    created() {
      this.getList();
      this.getDicts("sys_data_status").then(response => {
        this.statusOptions = response.data;
      });
      listCmsClass(this.queryParam).then(response => {
        this.cmsClassType = response.data;
      })
    },
    mounted() {
    },
    watch: {
      $route(to, from) {
        //from 从哪来
        //to //到哪去
        let path = from.path;
        //console.log("path==="+path)
        if ("/cms/notice/data" == path) {
          //刷新页面
          this.getList();
        } else {
          let index = path.lastIndexOf("/");
          if (index > -1) {
            path = path.substr(0, index);
            if ("/cms/notice/data" == path) {
              //刷新页面
              this.queryParams.pageNum = 1
              this.getList();
            }
          }
        }
      }
    },
    methods: {
      /** 查询(资讯/平台/公告)信息列表 */
      getList() {
        this.loading = true;
        console.log(this.queryParams);
        listCms(this.queryParams).then(response => {
          this.cmsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          cmsUid: null,
          cmsType: null,
          cmsTitle: null,
          titleImgUrl: null,
          cmsContent: null,
          cmsLink: null,
          publishTime: null,
          publishUser: null,
          dataPriority: 10,
          dataStatus: "0",
          createUid: null,
          createName: null,
          createTime: null,
          updateUid: null,
          updateName: null,
          updateTime: null,
          recommend: "0",
          titleVideoUrl: null,
          cmsClassCode: null,
          cmsClassPcode: null,
          platformUid: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.cmsUid)
        this.names = selection.map(item => item.cmsTitle);
        this.single = selection.length !== 1
        this.multiple = !selection.length
        //用于禁用删除
        if (this.multiple == false) {
          for (var i = 0; i < selection.length; i++) {
            var element = selection[i];
            if ("1" === element.dataStatus) {
              this.multiple = true;
              break;
            }
          }
        }
      },
      handleStatusChange(row) {
        let text = row.dataStatus === "0" ? "无效" : "有效";
        this.$confirm('确定要把业务标题为"' + row.cmsTitle + '",设为' + text + '吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateCmsStatus(row.cmsUid, row.dataStatus);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function() {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$router.push("/cms/notice/data");

        /*this.reset();
        this.open = true;
        this.title = "添加公告信息";
        //富文本编辑器神坑处理
        this.$nextTick(function() {
          console.log(document.querySelectorAll('.el-input__inner'))
          let inputDom=document.querySelectorAll('.el-input__inner')[6];
          inputDom.focus();
          //inputDom.blur();
        });*/
      },
      /** 查看详情按钮操作 **/
      handleShowDetail(row) {
        this.$router.push("/cms/notice/detail/" + row.cmsUid);
      },
      handCloseDetail() {
        this.viewOpen = false
        this.showData = []
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        //this.reset();
        const cmsUid = row.cmsUid || this.ids
        this.$router.push("/cms/notice/data/" + cmsUid);

       /* getCms(cmsUid).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改公告信息";
          //富文本编辑器神坑处理
          this.$nextTick(function() {
            console.log(document.querySelectorAll('.el-input__inner'))
            let inputDom=document.querySelectorAll('.el-input__inner')[6];
            inputDom.focus();
            //inputDom.blur();
          });
        });*/
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.cmsUid != null) {
              updateCms(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.cmsType = "notice";
              if (this.form.cmsClassCode) {
                this.form.cmsClassPcode = "gonggao"
              }
              addCms(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },


      /** 删除按钮操作 */
      handleDelete(row) {
        const cmsUids = row.cmsUid || this.ids;
        const names = row.cmsTitle || this.names;
        this.$confirm('是否确认删除标题为"' + names + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCmsN(cmsUids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
    }
  };
</script>
